<template>
  <app-container>
    <app-block>
      <zm-form :model="searchForm" ref="searchForm" inline>
        <zm-tabs
          v-model="searchForm.dataType"
          :list="dataTypeList"
          @tab-click="tabType"
          class="mb20"
        ></zm-tabs>
        <zm-form-item prop="orderNo">
          <zm-input class="w200" v-model.trim="searchForm.orderNo" placeholder="请输入销售单号" />
        </zm-form-item>
        <zm-form-item label prop="invoiceContent">
          <zm-input v-model="searchForm.invoiceContent" placeholder="请输入开票主体" class="w300" />
        </zm-form-item>
        <zm-form-item label prop="activeEndTime">
          <zm-date-picker
            type="datetimerange"
            :target="searchForm"
            start-key="activeStartTime"
            end-key="activeEndTime"
            start-placeholder="激活开始日期"
            end-placeholder="激活结束日期"
          />
        </zm-form-item>
        <zm-form-item label prop="refundEndTime">
          <zm-date-picker
            type="datetimerange"
            :target="searchForm"
            start-key="refundStartTime"
            end-key="refundEndTime"
            start-placeholder="退货开始日期"
            end-placeholder="退货结束日期"
          />
        </zm-form-item>
        <zm-form :model="searchMore" inline class="dib">
          <zm-form-item label prop="saleOrderType">
            <zm-data-select
              v-model="searchMore.saleOrderType"
              k1="saleOrderType"
              placeholder="销售单类型"
              class="w200"
            ></zm-data-select>
          </zm-form-item>
          <zm-form-item label prop="productType">
            <zm-data-select
              v-model="searchMore.productType"
              k1="productType"
              placeholder="产品类型"
              class="w200"
            ></zm-data-select>
          </zm-form-item>
          <!-- 销售单查询及导出 -->
          <zm-form-item label prop="businessScene">
            <zm-data-select
              v-model="searchMore.businessScene"
              k1="businessScene"
              class="w200"
              :has-all="true"
              :all-value="'-1'"
              placeholder="业务场景"
            >
            </zm-data-select>
          </zm-form-item>

          <span v-if="isCheckPass">
            <zm-form-item prop="operatorId" v-if="searchForm.dataType !== '1'">
              <zm-data-select
                v-model="searchMore.operatorId"
                multiple
                :list="operatorList"
                placeholder="所属业务员"
                class="w200"
              ></zm-data-select>
            </zm-form-item>
            <zm-form-item prop="saleOrderName">
              <zm-input
                class="w200"
                v-model="searchMore.saleOrderName"
                placeholder="请输入销售单名称"
              />
            </zm-form-item>
            <zm-form-item label prop="customerType">
              <zm-data-select
                v-model="searchMore.customerType"
                k1="customerType"
                placeholder="客户类型"
                class="w200"
              ></zm-data-select>
            </zm-form-item>
            <zm-form-item label prop="tradeType">
              <zm-data-select
                v-model="searchMore.tradeType"
                api="getDictList"
                :params="{ type: 'tradeType' }"
                multiple
                str
                placeholder="客户所属行业"
                class="w200"
              ></zm-data-select>
            </zm-form-item>
            <zm-form-item label prop="customerName">
              <zm-input
                class="w200"
                v-model="searchMore.customerName"
                placeholder="请输入客户名称"
              />
            </zm-form-item>

            <div class="dib">
              <zm-form-item label prop="dateType">
                <zm-data-select
                  v-model="searchMore.dateType"
                  :list="dateTypeList"
                  placeholder="日期类型"
                  class="w200"
                ></zm-data-select>
              </zm-form-item>
              <zm-form-item prop="startDate">
                <zm-date-picker
                  :target="searchMore"
                  start-key="startDate"
                  end-key="endDate"
                  class="w320"
                />
              </zm-form-item>
            </div>
            <zm-form-item label prop="productId">
              <zm-data-select
                v-model="searchMore.productId"
                api="getProductList"
                placeholder="销售产品"
                class="w200"
              ></zm-data-select>
            </zm-form-item>
            <zm-form-item prop="saleOrderStatus" v-if="isCheckPass">
              <zm-data-select
                v-model="saleOrderStatus"
                multiple
                :list="this.$auth.getBaseDataByType('orderStatus')"
                placeholder="订单状态"
                class="w200"
              ></zm-data-select>
            </zm-form-item>
            <zm-form-item prop="payStatus" v-if="isCheckPass">
              <zm-data-select
                v-model="payStatus"
                multiple
                :list="this.$auth.getBaseDataByType('paymentStatus')"
                placeholder="回款状态"
                class="w200"
              ></zm-data-select>
            </zm-form-item>
          </span>
        </zm-form>

        <zm-form-item>
          <zm-button @click="onSearch" t="search"></zm-button>
          <zm-button @click="toReset" t="reset"></zm-button>
          <zm-button type="success" @click="showSelectType = true">
            新增
          </zm-button>
          <zm-button
            type="warning"
            @click="isShowExportType"
            v-if="['1', '3'].includes(searchForm.checkStatus)"
          >
            导出
          </zm-button>
          <div class="dib ml10">
            <zm-button size="mini" @click="onUpLoad">
              上传
            </zm-button>
            <zm-upload
              ref="zmUpload"
              v-show="false"
              :http-request="fileUpload"
              accept=".rar,.zip,.doc,.docx,.pdf,.png,.jpg,.pptx"
              :limit="1"
              :single-file-size="5"
            >
            </zm-upload>
          </div>
          <div class="dib ml10">
            <zm-button size="mini" @click="onDownLoad">
              下载
            </zm-button>
            <!-- <zm-enclosure
              ref="zmEnclosure"
              v-show="false"
              :file-url="fileUrl"
            ></zm-enclosure> -->
          </div>
        </zm-form-item>
        <div>
          <zm-form-item label="审批状态:" prop="">
            <zm-data-radio
              is-btn
              v-model="searchForm.checkStatus"
              k1="checkStatus"
              @change="onSearch"
            />
          </zm-form-item>
        </div>
        <!--      <div>
          <zm-form-item label="订单状态:" prop="" v-if="isCheckPass">
            <zm-data-radio
              is-btn
              v-model="searchForm.saleOrderStatus"
              has-all
              k1="orderStatus"
              @change="onSearch"
            />
          </zm-form-item>
        </div> -->
        <div>
          <!--           <zm-form-item label="回款状态:" prop="" v-if="isCheckPass">
            <zm-data-radio
              is-btn
              v-model="searchForm.payStatus"
              has-all
              k1="paymentStatus"
              @change="onSearch"
            />
          </zm-form-item> -->
        </div>
        <div>
          <zm-form-item label="附件状态:" prop="">
            <zm-data-radio
              is-btn
              v-model="searchForm.uploadStatus"
              :list="uploadStatusList"
              @change="onSearch"
            />
          </zm-form-item>
        </div>
        <div
          v-if="
            searchForm.checkStatus === '3' &&
              (searchMore.saleOrderType === '1' || searchMore.saleOrderType === '2')
          "
        >
          <zm-form-item label="回执状态:" prop="">
            <zm-data-radio
              is-btn
              v-model="searchForm.receiptStatus"
              :list="receiptStatusList"
              @change="onSearch"
            />
          </zm-form-item>
        </div>
      </zm-form>
      <zm-table-data
        ref="multipleTable"
        class="mt10"
        :data="tableParams.data"
        :columns="columns"
        :fetch="loadList"
        :table-params="tableParams"
        :config-header="searchForm.checkStatus === '3' ? true : false"
        :show-page="true"
        :mutilple="true"
        :store-key="SOTRE_KEY_SALE_ORDER_LIST"
      >
      </zm-table-data>
    </app-block>
    <select-type
      v-if="showSelectType"
      v-model="showSelectType"
      @after-save="onSelectType"
    ></select-type>
    <export-type
      ref="exportTypeRef"
      v-if="showExportType"
      v-model="showExportType"
      :params="{ ...searchForm, ...searchMore, orderId: selectedIds }"
    ></export-type>
    <new-sale
      v-if="newVisible"
      v-model="newVisible"
      :row-info="rowInfo"
      @after-save="onSearch"
    ></new-sale>
    <detail-sale
      v-if="detailVisible"
      v-model="detailVisible"
      :business-id="detailId"
      @after-save="onSearch"
      type="Sale"
    ></detail-sale>
    <down-type
      v-if="showDownTypeParams.visible"
      v-model="showDownTypeParams.visible"
      :params="showDownTypeParams.params"
    ></down-type>
  </app-container>
</template>

<script>
import tableMixin from '@/mixins/zmTableMixin'
import saleOrderApi from '@/api/src/saleOrder'
import approveProcessApis from '@/api/src/approve'
import draft from '@/api/src/draft'
import SelectType from './components/SelectType'
import ExportType from './components/ExportType'
import DownType from './components/DownType'
import NewSale from './New'

import DetailSale from '@/components/DetailContainer'
import { SOTRE_KEY_SALE_ORDER_LIST } from '@/model/tableStoreKey'
import { columns, dataTypeList, dateTypeList, uploadStatusList, receiptStatusList } from './const'
import publicApis from '@/api/src/public'
import ZmUpload from '@/components/ZmUpload/components/main'
import uploadApis from '@/api/src/upload'
export default {
  name: 'SaleOrderList',
  components: {
    SelectType,
    ExportType,
    NewSale,
    DetailSale,
    ZmUpload,
    DownType
  },
  mixins: [tableMixin],
  data() {
    return {
      dataTypeList,
      dateTypeList,
      SOTRE_KEY_SALE_ORDER_LIST,
      uploadStatusList,
      receiptStatusList,
      showSelectType: false,
      showExportType: false,
      showDownTypeParams: {
        visible: false,
        params: {}
      },
      newVisible: false,
      rowInfo: {},
      detailVisible: false,
      detailId: '',
      saleOrderStatus: [],
      payStatus: [],
      searchForm: {
        dataType: '-1',
        orderNo: '',
        code: '',
        checkStatus: '3',
        saleOrderStatus: '-1',
        payStatus: '-1',
        uploadStatus: '-1',
        receiptStatus: '-1',
        invoiceContent: '',
        activeStartTime: '',
        activeEndTime: '',
        refundStartTime: '',
        refundEndTime: ''
      },
      // operatorId: [],
      searchMore: {
        operatorId: '',
        saleOrderName: '',
        customerType: '',
        tradeType: '',
        customerName: '',
        saleOrderType: '',
        dateType: '',
        startDate: '',
        endDate: '',
        productType: '',
        productId: '',
        businessScene: '' // 客情销售单业务场景
      },
      operatorList: [],
      fileUrl: ''
    }
  },
  computed: {
    columns() {
      return columns(this)
    },
    isSalePage() {
      return this.searchForm.checkStatus === '3' || this.searchForm.checkStatus === '0'
    },
    isCheckPass() {
      return this.searchForm.checkStatus === '3'
    },
    selectedIds() {
      if (this.isSalePage) {
        return this.getSelectionIds().join(',')
      } else {
        return this.getSelectionIds('relationId').join(',')
      }
    },
    selectedSaleOrderTypeIds() {
      return this.getSelectionIds('type').join(',')
    }
  },
  watch: {},
  created() {
    this.searchMore.operatorId = (this.$route.query && this.$route.query.accountId) || '' // 数据简报 详情 订单数 跳转 销售单列表页

    console.log(this.searchMore.operatorId, '========125=====')
    const _searchParams =
      this.$route.query.searchParams && JSON.parse(this.$route.query.searchParams)
    console.log(_searchParams, '_searchParams')
    if (_searchParams) {
      // this.searchMore.dateType = _searchParams.endTime ? '1' : ''
      this.searchForm.activeStartTime = _searchParams.startTime + ' 00:00:00'
      this.searchForm.activeEndTime = _searchParams.endTime + ' 23:59:59'
    }
    console.log(this.searchForm)
    this.getOperator()
  },
  methods: {
    isShowExportType() {
      this.showExportType = true
      if (this.searchForm.checkStatus === '1') {
        this.$nextTick(() => {
          this.$refs.exportTypeRef.submit()
        })
      }
    },
    async getOperator() {
      const _res = await publicApis.getSaleList({
        userType: this.searchForm.dataType
      })
      this.operatorList = _res
    },
    onCopy(row) {
      console.log(row)
      const id = this.isSalePage ? row.id : row.relationId
      this.$msg.confirm('确认复制吗?', '提示').then(async () => {
        const res = await saleOrderApi.copy({ id: id })
        this.$message.success('复制成功!')
        this.onSearch()
      })
    },
    // onSearch() {
    // console.log(this.operatorId)
    // this.searchMore.operatorId = this.operatorId.join(',')
    // this.clearSelection()
    // this.$set(this.tableParams, 'page', 1)
    // this.loadList && this.loadList()
    // },
    async loadList() {
      let _res
      if (this.isSalePage) {
        let apiParams
        if (this.searchForm.checkStatus === '0') {
          apiParams = {
            dataType: this.searchForm.dataType,
            checkStatus: this.searchForm.checkStatus,
            orderNo: this.searchForm.orderNo,
            saleOrderType: this.searchMore.saleOrderType,
            productType: this.searchMore.productType,
            uploadStatus: this.searchForm.uploadStatus,

            businessScene: this.searchForm.businessScene
          }
        } else {
          let operatorId =
            this.searchForm.dataType === '1' || !Array.isArray(this.searchMore.operatorId)
              ? ''
              : this.searchMore.operatorId.join(',')
          this.searchMore.saleOrderStatus = this.saleOrderStatus.length
            ? this.saleOrderStatus.join(',')
            : '-1'
          this.searchMore.payStatus = this.payStatus.length ? this.payStatus.join(',') : '-1'
          apiParams = {
            ...this.searchForm,
            ...this.searchMore,
            operatorId
          }
        }
        _res = await saleOrderApi.getPageList(this.assignQuery(apiParams))
      } else {
        let params = {
          dataType: this.searchForm.dataType,
          checkStatus: this.searchForm.checkStatus,
          code: this.searchForm.orderNo,
          saleOrderType: this.searchMore.saleOrderType,
          productType: this.searchMore.productType,
          businessScene: this.searchForm.businessScene,
          type: '3,4,5,9,10,12,13'
        }
        _res = await draft.getPageList(this.assignQuery(params))
      }
      this.initialTableData(_res.list, _res.count)
    },
    tabType() {
      this.onSearch()
      this.getOperator()
    },
    toReset() {
      this.searchMore = {
        operatorId: '',
        saleOrderName: '',
        customerType: '',
        tradeType: '',
        customerName: '',
        saleOrderType: '',
        dateType: '',
        startDate: '',
        endDate: '',
        productType: '',
        productId: '',
        businessScene: '' // 客情销售单业务场景
      }
      this.saleOrderStatus = []
      this.payStatus = []
      this.onReset()
    },
    onSelectType(type) {
      // 1日常销售单 2特殊销售单 3客情销售单  5客诉销售单
      this.rowInfo = {
        type: type,
        id: ''
      }
      console.log(type, 'type=')
      this.newVisible = true
      this.$nextTick(() => {
        this.showSelectType = false
      })
    },
    onDetail(row) {
      this.detailId = this.isSalePage ? row.id : row.relationId
      this.detailVisible = true
    },
    onEdit(row) {
      this.newVisible = true
      this.rowInfo = {
        id: this.isSalePage ? row.id : row.relationId,
        type: row.type
      }
    },
    async onDelete(row) {
      // 已撤销和被驳回 用api/draft/delete
      this.$msg.confirm('确认删除吗?', '提示').then(async () => {
        this.isSalePage
          ? await saleOrderApi.delete({
            id: row.id
          })
          : await draft.delete({ id: row.id })
        this.$message.success('删除成功!')
        this.onSearch()
      })
    },
    async onSubmit(row) {
      let processType
      if (row.checkStatus === '0') {
        switch (+row.type) {
          case 1:
            processType = 3
            break
          case 2:
            processType = 4
            break
          case 3:
            processType = 5
            break
          case 4:
            processType = 9
            break
          case 5:
            processType = 10
            break
          case 6:
            processType = 12
            break
          case 7:
            processType = 13
            break
        }
      } else {
        processType = row.type
      }
      await approveProcessApis.submit({
        businessId: this.isSalePage ? row.id : row.relationId,
        processType: processType,
        linkName: row.name
      })
      this.$message.success('成功提交审批!')
      this.onSearch()
    },
    async onReject(row) {
      this.$msg.confirm('该审批流已开始，确定撤销审批？', '撤销审批').then(async () => {
        await approveProcessApis.cancel({
          businessId: this.isSalePage ? row.id : row.relationId,
          processType: row.type
        })
        this.$msg.success()
        this.onSearch()
      })
    },
    onUpLoad() {
      if (!this.selectedIds) {
        this.$message.warning('请先选择数据')
        return
      }
      this.$refs.zmUpload.handelChoose()
    },
    async fileUpload(data) {
      let params = new FormData()
      params.append('fileData', data.file)
      const res = await uploadApis.uploadFile(params)
      const _data = {
        orderId: this.selectedIds,
        enclosureUrl: res.url,
        enclosureName: res.name
      }
      await saleOrderApi.changeFile(_data)
      this.loadList()
      return res.url
    },
    async onDownLoad() {
      if (!this.selectedIds) {
        this.$message.warning('请先选择数据')
        return
      }
      let params = {
        ...this.searchForm,
        ...this.searchMore,
        orderId: this.selectedIds,
        saleOrderType: this.selectedSaleOrderTypeIds
      }
      this.showDownTypeParams = {
        visible: true,
        params: params
      }
    }
  }
}
</script>
